package redis

import (
	"context"
	"sync"
	"time"

	"github.com/go-redis/redis/v8"
)

var GlobalRedis *redis.Client
var once sync.Once = sync.Once{}

func Setup() error {
	var err error
	once.Do(func() {
		RedisCli := redis.NewClient(&redis.Options{
			Addr:         "192.168.31.70:16379",
			Password:     "",
			DB:           0,
			ReadTimeout:  time.Second * 5,
			WriteTimeout: time.Second * 5,
		})
		ctx := context.Background()
		if cmd := RedisCli.Ping(ctx); cmd.Err() != nil {
			err = cmd.Err()
			return
		}
		GlobalRedis = RedisCli
	})
	return err
}

func Close() {
	if GlobalRedis != nil {
		GlobalRedis.Close()
	}
	GlobalRedis = nil
}

func Set(key string, value string) error {
	cmd := GlobalRedis.Set(context.Background(), key, value, 0)
	if err := cmd.Err(); err != nil {
		return err
	}
	return nil
}

func Get(key string) (string, error) {
	cmd := GlobalRedis.Get(context.Background(), key)
	if err := cmd.Err(); err != nil {
		return "", err
	}
	return cmd.Val(), nil
}

func Del(key string) (bool, error) {
	cmd := GlobalRedis.Del(context.Background(), key)
	if err := cmd.Err(); err != nil {
		return false, err
	}
	return true, nil
}

func SetNxEx(key string, val any, expire time.Duration) (bool, error) {
	cmd := GlobalRedis.SetNX(context.Background(), key, val, expire)
	if err := cmd.Err(); err != nil {
		return false, err
	}
	return cmd.Val(), nil
}

func HSet(key, field, value string) error {
	cmd := GlobalRedis.HSet(context.Background(), key, field, value)
	if err := cmd.Err(); err != nil {
		return err
	}
	return nil
}

func HGet(key, field string) (string, error) {
	cmd := GlobalRedis.HGet(context.Background(), key, field)
	if err := cmd.Err(); err != nil {
		return "", err
	}
	return cmd.Val(), nil
}

func HGetAll(key string) (map[string]string, error) {
	cmd := GlobalRedis.HGetAll(context.Background(), key)
	if err := cmd.Err(); err != nil {
		return nil, err
	}
	return cmd.Val(), nil
}
